import { defineStore } from 'pinia';
import { ref, getCurrentInstance } from 'vue';
import api from '@/http/api';

export const useVisualCompStore = defineStore('visualComp', () => {
  const loading = ref(false);
  const visualCompList = ref([]);
  visualCompList.value['vc-page'] = {name: '页面', styleList: []};

  const setVisualComp = (compName, comp) => {
    visualCompList.value[compName] = comp;
  };

  const getVisualComp = async(type) => {
    let compName = 'vc-' + type;
    if (visualCompList.value && visualCompList.value[compName]) {
      return visualCompList.value[compName];
    }

    if (loading.value) {
      await sleep(100);
      return await getVisualComp(type);
    }

    loading.value = true;
    const res = await api.post('/visual-comp/queryBy', {id: type});

    if (res.code === '1') {
      let data = res.data || {};
      getCurrentInstance().component(compName, data.compTpl);
      setVisualComp(compName, {name: compName, styleList: data.styleList || []});
      loading.value = false;
      return data;
    } else {
      loading.value = false;
      return {};
    }
  };

  const sleep = async (d) => {
    return new Promise((resolve) => setTimeout(resolve, d))
  };

  return {
    getVisualComp,
    setVisualComp
  };
});
